package com.agileboot.domain.airport.inspection;

import com.agileboot.common.core.page.PageDTO;
import com.agileboot.domain.common.command.BulkOperationCommand;
import com.agileboot.domain.airport.inspection.command.AddSirInspectionCommand;
import com.agileboot.domain.airport.inspection.command.UpdateSirInspectionCommand;
import com.agileboot.domain.airport.inspection.db.SirInspectionEntity;
import com.agileboot.domain.airport.inspection.db.SirInspectionService;
import com.agileboot.domain.airport.inspection.dto.SirInspectionDTO;
import com.agileboot.domain.airport.inspection.model.SirInspectionModel;
import com.agileboot.domain.airport.inspection.model.SirInspectionModelFactory;
import com.agileboot.domain.airport.inspection.query.SirInspectionQuery;
import com.agileboot.domain.airport.inspectionCheck.db.SirInspectionCheckEntity;
import com.agileboot.domain.airport.inspectionCheck.db.SirInspectionCheckService;
import com.agileboot.domain.airport.inspectionUser.db.SirInspectionUserEntity;
import com.agileboot.domain.airport.inspectionUser.db.SirInspectionUserService;
import com.agileboot.domain.system.dept.DeptApplicationService;
import com.agileboot.domain.system.dept.db.SysDeptService;
import com.agileboot.domain.system.dept.dto.DeptDTO;
import com.agileboot.domain.system.dept.db.SysDeptEntity;
import com.agileboot.domain.system.user.db.SysUserEntity;
import com.agileboot.domain.system.user.db.SysUserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author valarchie
 */
@Service
@RequiredArgsConstructor
public class SirInspectionApplicationService {

    private final SirInspectionModelFactory inspectionModelFactory;
    private final DeptApplicationService deptApplicationService;
    private final SysUserService sysUserService;
    @Qualifier("sirInspectionServiceImpl")
    private final SirInspectionService inspectionService;
    // 使用 SirInspectionUserService 替换 SirInspectionUserMapper
    private final SirInspectionUserService sirInspectionUserService;
    private final SirInspectionCheckService sirInspectionCheckService;

    private final SysDeptService sysDeptService;

    public PageDTO<SirInspectionDTO> getInspectionList(SirInspectionQuery query) {
        Page<SirInspectionEntity> page = inspectionService.page(query.toPage(), query.toQueryWrapper());
        List<SirInspectionDTO> records = convertEntitiesToDTOs(page.getRecords());
        return new PageDTO<>(records, page.getTotal());
    }

    public List<SirInspectionDTO> getInspectionListAll(SirInspectionQuery query) {
        List<SirInspectionEntity> all = inspectionService.list(query.toQueryWrapper());
        return convertEntitiesToDTOs(all);
    }

    public SirInspectionDTO getInspectionInfo(Long inspectionId) {
        SirInspectionEntity byId = inspectionService.getById(inspectionId);
        if (byId == null) {
            return null;
        }
        return convertEntitiesToDTOs(List.of(byId)).get(0);
    }

    private List<SirInspectionDTO> convertEntitiesToDTOs(List<SirInspectionEntity> entities) {
        if (entities.isEmpty()) {
            return Collections.emptyList();
        }

        // 收集所有检查计划 ID 和部门 ID
        List<Long> inspectionIds = entities.stream()
                .map(SirInspectionEntity::getInspectionId)
                .collect(Collectors.toList());
        List<Long> deptIds = entities.stream()
                .map(SirInspectionEntity::getInspectionDeptId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 批量获取检查人员关联记录和部门实体
        List<SirInspectionUserEntity> inspectionUserEntities = sirInspectionUserService.getByInspectionIds(inspectionIds);
        List<SysDeptEntity> deptEntities = sysDeptService.getByDeptIds(deptIds);

        // 将部门实体转换为 Map 方便查找
        Map<Long, DeptDTO> deptMap = deptEntities.stream()
                .collect(Collectors.toMap(SysDeptEntity::getDeptId, dept -> new DeptDTO(dept)));

        // 将检查人员关联记录按检查计划 ID 分组
        Map<Long, List<SirInspectionUserEntity>> inspectionUserMap = inspectionUserEntities.stream()
                .collect(Collectors.groupingBy(SirInspectionUserEntity::getInspectionId));

        // 收集所有需要查询的用户 ID，添加 creatorId
        Set<Long> allUserIds = inspectionUserEntities.stream()
                .map(SirInspectionUserEntity::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 添加 entities 的 creatorId 到 allUserIds
        entities.stream()
                .map(SirInspectionEntity::getCreatorId)
                .filter(Objects::nonNull)
                .forEach(allUserIds::add);

        // 批量获取用户信息
        List<SysUserEntity> userEntities = sysUserService.getByUserIds(new ArrayList<>(allUserIds));
        Map<Long, SysUserEntity> userMap = userEntities.stream()
                .collect(Collectors.toMap(SysUserEntity::getUserId, user -> user));

        // 批量获取所有检查项
        List<SirInspectionCheckEntity> inspectionCheckEntities = sirInspectionCheckService.getByInspectionIds(inspectionIds);
        // 将检查项按检查计划 ID 分组
        Map<Long, List<SirInspectionCheckEntity>> inspectionCheckMap = inspectionCheckEntities.stream()
                .collect(Collectors.groupingBy(SirInspectionCheckEntity::getInspectionId));

        return entities.stream().map(entity -> {
            SirInspectionDTO dto = new SirInspectionDTO(entity);

            // 设置部门名称
            if (entity.getInspectionDeptId() != null) {
                DeptDTO dept = deptMap.get(entity.getInspectionDeptId());
                dto.setDeptName(dept != null ? dept.getDeptName() : null);
            }

            List<SirInspectionUserEntity> userEntitiesPerInspection = inspectionUserMap.getOrDefault(entity.getInspectionId(), Collections.emptyList());
            List<String> userNames = userEntitiesPerInspection.stream()
                    .map(userEntity -> {
                        SysUserEntity user = userMap.get(userEntity.getUserId());
                        if (user != null) {
                            // 根据 leaderFlag 拼接前缀
                            if ("1".equals(userEntity.getLeaderFlag())) {
                                return "(组长：" + user.getUsername()+")";
                            }
                            return user.getUsername();
                        }
                        return null;
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            dto.setUserNameList(userNames);

            // 设置创建者姓名
            if (entity.getCreatorId() != null) {
                SysUserEntity creator = userMap.get(entity.getCreatorId());
                if (creator != null) {
                    dto.setCreateBy(creator.getUsername());
                }
            }

            // 设置检查类型详情
            String inspectionCode = entity.getInspectionCode();
            if (inspectionCode != null && inspectionCode.length() >= 4) {
                String typeValue = inspectionCode.substring(0, 4);
                String typeLabel = getTypeLabel(typeValue);
                dto.setInspectionTypeDetail(new SirInspectionDTO.InspectionTypeDetail(typeLabel, typeValue));
            }

            // 统计检查项目数量和完成的检查项目数量
            List<SirInspectionCheckEntity> checkEntities = inspectionCheckMap.getOrDefault(entity.getInspectionId(), Collections.emptyList());
            long checkItemCount = checkEntities.size();
            // 修改检查完成数量统计逻辑，当检查结果不为 "0" 时认为已检查
            long completedCheckCount = checkEntities.stream()
                    .filter(check -> check.getInspectionResult() != null && !check.getInspectionResult().equals("0"))
                    .count();

            // 计算检查进度
            Double checkProgress = checkItemCount == 0 ? 0.0 : (double) completedCheckCount / checkItemCount * 100;

            // 设置检查项目数量和检查进度
            dto.setCheckItemCount(checkItemCount);
            dto.setCheckProgress(checkProgress);

            return dto;
        }).collect(Collectors.toList());
    }

    public void addInspection(AddSirInspectionCommand addCommand) {
        SirInspectionModel inspectionModel = inspectionModelFactory.create();
        inspectionModel.loadFromAddCommand(addCommand);
        inspectionModel.insert();

        Long inspectionId = inspectionModel.getInspectionId();
        String checkUseridList = addCommand.getCheckUseridList();
        Long checkUserId = addCommand.getCheckUserId();

        if (checkUseridList != null && !checkUseridList.isEmpty()) {
            String[] userIds = checkUseridList.split(",");
            List<SirInspectionUserEntity> userEntities = new ArrayList<>();

            for (String userIdStr : userIds) {
                Long userId = Long.parseLong(userIdStr.trim());
                SirInspectionUserEntity userEntity = new SirInspectionUserEntity();
                userEntity.setInspectionId(inspectionId);
                userEntity.setUserId(userId);
                userEntity.setLeaderFlag(userId.equals(checkUserId) ? "1" : "0");
                userEntities.add(userEntity);
            }

            sirInspectionUserService.saveBatch(userEntities);
        }
    }

    public void updateInspection(UpdateSirInspectionCommand updateCommand) {


        SirInspectionModel inspectionModel = inspectionModelFactory.loadById(updateCommand.getInspectionId());
        inspectionModel.loadFromUpdateCommand(updateCommand);
        inspectionModel.updateById();

        Long inspectionId = inspectionModel.getInspectionId();
        String checkUseridList = updateCommand.getCheckUseridList();
        Long checkUserId = updateCommand.getCheckUserId();


        //更新检查小组名单人员
        if (checkUseridList != null && !checkUseridList.isEmpty()) {
            // 删除旧的检查人员关联记录
            sirInspectionUserService.deleteByInspectionIds(List.of(inspectionId));
            String[] userIds = checkUseridList.split(",");
            List<SirInspectionUserEntity> userEntities = new ArrayList<>();

            for (String userIdStr : userIds) {
                Long userId = Long.parseLong(userIdStr.trim());
                SirInspectionUserEntity userEntity = new SirInspectionUserEntity();
                userEntity.setInspectionId(inspectionId);
                userEntity.setUserId(userId);
                userEntity.setLeaderFlag(userId.equals(checkUserId) ? "1" : "0");
                userEntities.add(userEntity);
            }

            // 保存新的检查人员关联记录
            sirInspectionUserService.saveBatch(userEntities);
        }
    }

    private String getTypeLabel(String typeValue) {
        switch (typeValue) {
            case "FDZC":
                return "法定自查";
            case "ZXJC":
                return "专项检查";
            case "AQZL":
                return "安全质量检查";
            default:
                return "未知类型";
        }
    }

    public void deleteInspection(BulkOperationCommand<Long> deleteCommand) {
        inspectionService.removeBatchByIds(deleteCommand.getIds());
    }

}